package net.viralpatel.docmanager.controller;
 
import java.io.IOException;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.sql.rowset.serial.SerialBlob;
import javax.sql.rowset.serial.SerialException;

import net.viralpatel.docmanager.model.Document;
import net.viralpatel.docmanager.service.DocumentService;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
 
@Controller
public class DocumentControllerImpl implements DocumentController {
     
    @Autowired
    private DocumentService documentService;
     
    /*
     * index method – 
     * This method uses list() method of DocumentDAO to fetch the list of all documents from database. 
     * Note that we have mapped request “/index” to this method. Thus Spring will automatically calls this method whenever it 
     * encounters this url in request.
     */
    /* (non-Javadoc)
	 * @see net.viralpatel.docmanager.controller.DocumentControllerI#index(java.util.Map)
	 */
    @RequestMapping("/index")
    public String index(Map<String, Object> map) {
        try {
            map.put("document", new Document());
            map.put("documentList", documentService.listDocuments());
        }catch(Exception e) {
            e.printStackTrace();
        }
 
        return "documents";
    }
    
    
    /*
     * save method – 
     * This method adds a new document to document list. The document details are fetched in Document object using @ModelAttribute annotation. 
     * Also note that the request “/save” is mapped with this method. The request method should also be POST. Once the document is added 
     * in document list, we redirect to /index.html page which in turn calls index() method to display document list to user. 
     * One more thing to note here is @RequestParam. We are mapping MultipartFile object using @RequestParam(“file”) annotation. 
     * Spring automatically detects “file” data from request and map it with MultipartFile object. This object is later converted to
     * BLOB object and set in the Document content. 
     */
 
    /* (non-Javadoc)
	 * @see net.viralpatel.docmanager.controller.DocumentControllerI#save(net.viralpatel.docmanager.model.Document, org.springframework.web.multipart.MultipartFile)
	 */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(
            @ModelAttribute("document") Document document,
            @RequestParam("file") MultipartFile file) {
         
         
        System.out.println("Name:" + document.getName());
        System.out.println("Desc:" + document.getDescription());
        System.out.println("File:" + file.getName());
        System.out.println("ContentType:" + file.getContentType());
         
        try {
            //Blob blob = Hibernate.createBlob(file.getInputStream());
             
            document.setFilename(file.getOriginalFilename());
            document.setContent(new SerialBlob(file.getBytes()));
            document.setContentType(file.getContentType());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SerialException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
         
        try {
            documentService.addDocument(document);
        } catch(Exception e) {
            e.printStackTrace();
        }
         
        return "redirect:/index.html";
    }
 
    /* (non-Javadoc)
	 * @see net.viralpatel.docmanager.controller.DocumentControllerI#download(java.lang.Integer, javax.servlet.http.HttpServletResponse)
	 */
    @RequestMapping("/download/{documentId}")
    public String download(@PathVariable("documentId")
            Integer documentId, HttpServletResponse response) {
         
        Document doc = documentService.getDocument(documentId);
        try {
            response.setHeader("Content-Disposition", "inline;filename=\"" +doc.getFilename()+ "\"");
            OutputStream out = response.getOutputStream();
            response.setContentType(doc.getContentType());
            IOUtils.copy(doc.getContent().getBinaryStream(), out);
            out.flush();
            out.close();
         
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
         
         
        return null;
    }
 
    /* (non-Javadoc)
	 * @see net.viralpatel.docmanager.controller.DocumentControllerI#remove(java.lang.Integer)
	 */
    @RequestMapping("/remove/{documentId}")
    public String remove(@PathVariable("documentId")
            Integer documentId) {
         
        documentService.removeFile(documentId);
         
        return "redirect:/index.html";
    }
}